﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using TBM.Filters;
using TBM.Attributes;

namespace TBM.Controllers
{
    public partial class SystemController : MasterController
    {
        [Description("模块配置")]
        [TBMAuthorize("系统配置", "模块配置")]
        public ActionResult ModuleSetting()
        {
            List<Models.ModuleItem> modules = new List<Models.ModuleItem>();
            List<Models.ModuleController> controllers = new List<Models.ModuleController>();

            cmd.CommandText = "select ID, PID, ControllerName, ControllerDescr, ActionName, ActionDescr, IsActived from dbo.Modules order by ControllerName";
            cmd.CommandType = CommandType.Text;

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    modules.Add(new Models.ModuleItem
                    {
                        ID = (int)dr["ID"],
                        PID = (int)dr["PID"],
                        ControllerName = dr["ControllerName"].ToString(),
                        ControllerDescr = dr["ControllerDescr"].ToString(),
                        ActionName = dr["ActionName"].ToString(),
                        ActionDescr = dr["ActionDescr"].ToString(),
                        IsActived = (bool)dr["IsActived"]
                    });
                }
            }

            var result = (from n in modules group n by new { n.ControllerDescr, n.ControllerName } into g select new { g.Key.ControllerDescr, g.Key.ControllerName }).ToList();

            foreach (var item in result)
            {
                List<Models.ModuleItem> items = modules.Where(a => a.ControllerName == item.ControllerName && a.PID == 0).ToList();
                Models.ModuleController mc = new Models.ModuleController();
                mc.ControllerName = item.ControllerName;
                mc.ControllerDescr = item.ControllerDescr;

                if (items.Any())
                {
                    mc.SubModule = new List<Models.ModuleItem>();
                    foreach (Models.ModuleItem sitem in items)
                    {
                        mc.SubModule.Add(sitem);
                        AppendItem(sitem, modules);
                    }
                }

                controllers.Add(mc);
            }

            ViewBag.Controllers = controllers;

            return PartialView();
        }

        /// <summary>
        /// 添加模块子项
        /// </summary>
        /// <param name="item"></param>
        /// <param name="modules"></param>
        private void AppendItem(Models.ModuleItem item, List<Models.ModuleItem> modules)
        {
            List<Models.ModuleItem> items = modules.Where(a => a.PID == item.ID).ToList();

            if (!items.Any()) return;

            item.SubModule = new List<Models.ModuleItem>();

            foreach (Models.ModuleItem sitem in items)
            {
                item.SubModule.Add(sitem);
                AppendItem(sitem, modules);
            }
        }


        [ParentAction("ModuleSetting")]
        [Description("更新模块状态")]
        [TBMAuthorize("系统配置", "更新模块状态")]
        public JsonResult UpdateModule()
        {
            JsonResult result = new JsonResult();

            cmd.CommandText = @"update M
	                                set M.IsActived = T.IsChecked
                                from dbo.Modules as M inner join
                                (select 
	                                M.ID, CAST(case when Item is null then 0 else 1 end as bit) as IsChecked 
	                                from 
		                                dbo.Modules as M left join fn_Split(@IDs, ',') as S on M.ID = S.Item) as T
                                on M.ID = T.ID";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@IDs", SqlDbType.VarChar, 8000);
            cmd.Parameters["@IDs"].Value = Core.CommandParamType.NullOrString(Request["id"]).ToString();

            Core.LangItem li = cmd.ExecuteNonQuery() > 0 ? Core.Lang.CMD_SUCCESS : Core.Lang.CMD_FAILED;

            result.Data = new Models.ExecuteResult
            {
                Result = li.Code == Core.Lang.CMD_SUCCESS.Code,
                Code = li.Code,
                Message = li.Message
            };

            return result;
        }
    }
}
